package org.shinetour.sms.service.impl;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.shinetour.sms.model.*;
import org.shinetour.sms.service.*;
import org.shinetour.sms.web.page.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description: 短信管理服务
 * @Author: ZhenHua Wang
 * @CreateDate: 2020/3/23 11:41
 */
@Service
public class SmsManageServiceImpl implements ISmsManageService {

    @Autowired
    ISmsRecordService smsRecordService;
    @Autowired
    ISmsTemplateService templateService;
    @Autowired
    ITemplateParamsService templateParamsService;
    @Autowired
    IRLSmsService supplierService;
    @Autowired
    ISmsErrorRecordService errorRecordService;


    /**
     * @Description: 查询短信发送记录
     * @Author: ZhenHua Wang
     * @CreateDate: 2020/3/23 11:39
     */
    @Override
    public Page<SmsRecord> listSmsRecord(Map<String, String> request) {
        QueryWrapper<SmsRecord> reqWrapper = new QueryWrapper<>();
        if (!StrUtil.isEmpty(request.get("iid"))) {
            reqWrapper.eq("iid", request.get("iid"));
        }
        if (!StrUtil.isEmpty(request.get("mobile"))) {
            reqWrapper.eq("mobile", request.get("mobile"));
        }
        if (!StrUtil.isEmpty(request.get("templateCode"))) {
            reqWrapper.eq("template_code", request.get("templateCode"));
        }
        if (!StrUtil.isEmpty(request.get("sendSuccess"))) {
            if ("0".equals(request.get("sendSuccess"))) {
                reqWrapper.eq("send_success", false);
            }
            if ("1".equals(request.get("sendSuccess"))) {
                reqWrapper.eq("send_success", true);
            }
        }

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (!StrUtil.isEmpty(request.get("beginTime"))) {
                reqWrapper.ge("success_time", sdf.parse(request.get("beginTime") + " 00:00:00"));
            }
            if (!StrUtil.isEmpty(request.get("endTime"))) {
                reqWrapper.le("success_time", sdf.parse(request.get("endTime") + " 23:59:59"));
            }
        } catch (Exception ex) {
        }

        Page<SmsRecord> page = smsRecordService.page(PageHelper.getPage(request), reqWrapper);

        return page;
    }

    /**
     * @Description: 根据iid查询模板
     * @Author: ZhenHua Wang
     * @CreateDate: 2020/4/16 9:41
     */
    @Override
    public SmsTemplate selectSmsTemplateById(Long iid) {
        return templateService.getById(iid);
    }


    /**
     * @Description: 查询模板列表
     * @Author: ZhenHua Wang
     * @CreateDate: 2020/3/23 11:40
     */
    @Override
    public Page<SmsTemplate> listSmsTemplate(Map<String, String> request) {
        QueryWrapper<SmsTemplate> reqWrapper = new QueryWrapper<>();
        if (!StrUtil.isEmpty(request.get("templateName"))) {
            reqWrapper.like("template_name", request.get("templateName"))
                    .or().like("template_alias", request.get("templateName"));
        }
        Page<SmsTemplate> page = templateService.page(PageHelper.getPage(request), reqWrapper);
        return page;
    }

    /**
     * @Description: 根据模板编号查询模板参数
     * @Author: ZhenHua Wang
     * @CreateDate: 2020/4/9 17:42
     */
    @Override
    public List<TemplateParams> listSmsTemplateParams(String templateCode) {
        QueryWrapper<TemplateParams> reqWrapper = new QueryWrapper();
        reqWrapper.eq("template_code", templateCode);
        return templateParamsService.list(reqWrapper);
    }

    /**
     * @Description: 新增或修改短信模板
     * @Author: ZhenHua Wang
     * @CreateDate: 2020/4/15 11:35
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultModel addOrEditTemplate(TemplateDTO template) {
        ResultModel res = new ResultModel();
        if (StrUtil.isEmpty(template.getTemplateCode())) {
            return res.error("模板编码为空，请检查后重试！");
        }
        if (StrUtil.isEmpty(template.getTemplateName())) {
            return res.error("模板名称为空，请检查后重试！");
        }
        if (StrUtil.isEmpty(template.getTemplateAlias())) {
            return res.error("模板别名为空，请检查后重试！");
        }
        if (StrUtil.isEmpty(template.getTemplateContent())) {
            return res.error("模板内容为空，请检查后重试！");
        }
        if (null == template.getParams() || template.getParams().isEmpty()) {
            return res.error("模板参数信息为空，请检查后重试！");
        }
        for (int i = 0; i < template.getParams().size(); i++) {
            if (null == template.getParams().get(i).getParamIndex()) {
                return res.error("模板参数序号为空，请检查后重试！");
            }
            if (null == template.getParams().get(i).getParamKey()) {
                return res.error("模板参数字段名为空，请检查后重试！");
            }
            if (null == template.getParams().get(i).getParamName()) {
                return res.error("模板参数名称为空，请检查后重试！");
            }
        }
        //模板的编码、名称、别名都不能重复
        QueryWrapper<SmsTemplate> reqWrapper = new QueryWrapper<SmsTemplate>()
                .eq("template_code", template.getTemplateCode())
                .or().eq("template_name", template.getTemplateName())
                .or().eq("template_alias", template.getTemplateAlias());
        SmsTemplate exist = templateService.getOne(reqWrapper);
        //编码或名称或别名的模板，但是IID不相同
        if (null != exist && template.getIid() != exist.getIid()) {
            return res.error("系统存在相同编码或名称或别名的模板，请检查后重试！");
        }
        template.setCreateTime(null != exist ? exist.getCreateTime() : new Date());

        //保存或更新短信模板
        boolean saveSuccess = templateService.saveOrUpdate((SmsTemplate) template);
        if (!saveSuccess) {
            return res.error("保存短信模板失败！");
        }
        template.getParams().forEach(t -> {
            t.setTemplateCode(template.getTemplateCode());
        });
        //删除现有参数，保存新的短信参数
        templateParamsService.remove(new QueryWrapper<TemplateParams>().eq("template_code", template.getTemplateCode()));
        templateParamsService.saveBatch(template.getParams());
        return res.success();
    }
}
